package lzupdater.gui.listeners;

import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;

import lzupdater.timing.CentralTimer;
import lzupdater.timing.TimedTask;
import lzupdater.timing.TimerMode;

//LZRosterUpdater, a java client to update LZRoster
//Copyright (C) 2008 Fraskor from Krasus (e-mail: fraskor@gmail.com)
//
//This file is part of LZRosterUpdater.
//
//LZRosterUpdater is free software: you can redistribute it and/or modify
//it under the terms of the GNU General Public License as published by
//the Free Software Foundation, either version 3 of the License, or
//(at your option) any later version.
//
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with this program.  If not, see <http://www.gnu.org/licenses/>.

/**
 * Focus listener that performed a task (defined by the user) after a specific
 * delai after the focus has been lost. If the component that register this
 * FocusListener gain the focus before the timer is up. The timer is deleted and
 * the task will not be performed (till the component lost the focus again).
 * 
 * @author Fraskor
 */
public abstract class FocusLostTask implements FocusListener, TimedTask {

	private double delaiMs;

	/**
	 * Constructor without delai between the lost of focus and the execution of
	 * the task
	 */
	public FocusLostTask() {
		this(-1);
	}

	/**
	 * Constructor with a delai between the lost of focus and the execution of
	 * the task
	 * 
	 * @param delaiMs
	 *            the delai in millisecondes
	 */
	public FocusLostTask(double delaiMs) {
		this.delaiMs = delaiMs;
	}

	/**
	 * {@inheritDoc}
	 */
	public void taskDone() {
	}

	/**
	 * {@inheritDoc}
	 */
	public void taskStopped() {
	}

	/**
	 * {@inheritDoc}
	 */
	public void focusGained(FocusEvent e) {
		CentralTimer.stopTimedTask(this);
	}

	/**
	 * {@inheritDoc}
	 */
	public void focusLost(FocusEvent e) {
		if (delaiMs > 0) {
			CentralTimer.resetTimedTask(this, delaiMs, TimerMode.onlyOnce());
		} else {
			performTask(System.nanoTime());
		}
	}
}
